package com.mocchira.music.radio;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;

import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class PlayListActivity extends ExpandableListActivity {
    
    private HotArtistManager manager;
    private String filter;
    
    private ProgressDialog progress = null;
    
    public enum CATEGORY {
        A_I,
        J_R,
        S_Z,
        OTHERS
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONArray hotList = manager.getHotTags();
            if (hotList == null) {
                this.sendEmptyMessageDelayed(0, 1000);
                return;
            }
            List<String> result = new ArrayList<String>();
            for (int i = 0; i < hotList.length(); i++) {
                try {
                    String artist = hotList.getString(i);
                    String dec = URLDecoder.decode(artist, "UTF-8");
                    if (isListed(filter, dec))
                        result.add(dec);
                } catch (Exception ex) {};
            }
            if (result.size() == 0) return;
            Collections.sort(result);
            TagBasedListAdapter adapter = new TagBasedListAdapter(result);
            PlayListActivity.this.setListAdapter(adapter);
            if (progress.isShowing())
                try {progress.dismiss();}catch (Exception nex){};
        }
    };
    
    private boolean isListed(String filter, String artist) {
        char top = Character.toLowerCase(artist.charAt(0));
        if (filter.equals(CATEGORY.A_I.name())) {
            return (top >= 'a' && top <= 'i');
        } else if (filter.equals(CATEGORY.J_R.name())) {
            return (top >= 'j' && top <= 'r');
        } else if (filter.equals(CATEGORY.S_Z.name())) {
            return (top >= 's' && top <= 'z');
        } else if (filter.equals(CATEGORY.OTHERS.name())) {
            return !Character.isLetter(top);
        }
        return false;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        filter = (String)bundle.get(R.string.bundle_artist + "");
        manager = HotArtistManager.getInstance(this);
        manager.getHotTags();
        handler.sendEmptyMessageDelayed(0, 1);
        if (progress == null)
            progress = ProgressDialog.show(PlayListActivity.this, "preparing...", "Download Tag List File");

    }
    
    public class TagBasedListAdapter extends BaseExpandableListAdapter {
        
        List<String> tags = new ArrayList<String>();
        
        public TagBasedListAdapter(List<String> tags) {
            this.tags = tags;
        }
        
        private List<String> getArtists(int groupPosition) {
            String tag = tags.get(groupPosition);
            String enc = null;
            try {
                enc = URLEncoder.encode(tag, "UTF-8");
            } catch (Exception ex) {return null;};
            List<String> artists = manager.getHotArtistsByTag(enc);
            return artists;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            List<String> artists = getArtists(groupPosition);
            if (artists == null)
                return null;
            else
                return (String)artists.get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return groupPosition * 1000 + childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            TextView textView = (TextView)convertView;
            if (convertView == null) {
                textView = new TextView(PlayListActivity.this);
                textView.setGravity(Gravity.LEFT);
                textView.setClickable(true);
                textView.setPadding(40, 3, 3, 3);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PlayListActivity.this, FMRPlayActivity.class);
                        Bundle bundle = new Bundle();
                        String artist = (String)((TextView)v).getText();
                        bundle.putString(R.string.bundle_artist+"", artist);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
            String artist = (String)getChild(groupPosition, childPosition);
            if (artist != null) {
                String dec = null;
                try {
                    dec = URLDecoder.decode(artist, "UTF-8");
                } catch (Exception ex) {dec = "";};
                textView.setText(dec);
            }
            return textView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<String> artists = getArtists(groupPosition);
            return artists == null ? 0: artists.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return (String)tags.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return tags.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            TextView textView = (TextView)convertView;
            if (convertView == null) {
                textView = new TextView(PlayListActivity.this);
                textView.setGravity(Gravity.LEFT);
                textView.setPadding(35, 3, 3, 3);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
            }
            textView.setText((String)getGroup(groupPosition));
            return textView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }
        
    }

}
